package cn.copera.dyy.web;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;

import cn.copera.dyy.service.ExchangeRuleService;

public class ImageFilter extends OncePerRequestFilter {
	@Autowired
	ExchangeRuleService exchangeRuleService;

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String url = request.getRequestURI();
		if(url.indexOf("X")!=-1){
			String[] ss = url.split("/");
			String fname = ss[3];

			
			File f = new File(getServletContext().getRealPath("/images") + "/"
					+ fname);
			if (!f.exists()) {
				File srcFile = new File(getServletContext().getRealPath("/images")
						+ "/" + fname.split("_")[0] + ".jpg");
				
				String[] params = fname.split("_")[1].replace(".jpg", "")
						.split("X");
				resizeImg(srcFile.getAbsolutePath(),f.getAbsolutePath(),Integer.parseInt(params[0]),Integer.parseInt(params[1]));
				
				
			}
		}
		

		filterChain.doFilter(request, response);
	}

	public static boolean resizeImg(String origin, String dest, int width,
			int height) {
		try {
			BufferedImage img = ImageIO.read(new File(origin));
			// origin width and height
			int imgWidth = img.getWidth();
			int imgHeight = img.getHeight();
			// check width and height
			float widthRate = (float) imgWidth / (float) width;
			float heightRate = (float) imgHeight / (float) height;
			float rate = widthRate > heightRate ? widthRate : heightRate;
			rewriteImg(origin, dest, 0, 0, (int) (imgWidth / rate),
					(int) (imgHeight / rate), BufferedImage.TYPE_INT_RGB);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static boolean rewriteImg(String origin, String dest, int x, int y,
			int width, int height, Integer scaleType) {
		try {
			// img's suffix
			String suffix = origin.substring(origin.lastIndexOf(".") + 1);
			// source image
			Image image = ImageIO.read(new File(origin));

			// get target
			BufferedImage tag = new BufferedImage(width, height, scaleType);
			Graphics g = tag.getGraphics();
			g.drawImage(image, x, y, width, height, null);
			g.dispose();

			// Graphics to ByteArrayOutputStream
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ImageIO.write(tag, suffix, bos);

			// write file
			FileOutputStream fos = new FileOutputStream(dest);
			fos.write(bos.toByteArray());
			fos.flush();
			fos.close();

			return true;
		} catch (Exception e) {
			return false;
		}
	}
}
